package com.qingke.stockdata.service;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.qingke.stockdata.mappers.UserMapper;
import com.qingke.stockdata.model.User;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	private final String slat = "s3*&*^%$&*(&_%^&*ip";
	
	public String register(User user) {

		try {

			System.out.println(userMapper);
			List<User> list = userMapper.selectUserAll();
			for (User user2 : list) {

				if(user.getUsername()!=null){
					
					if (user.getUsername().equals(user2.getUsername())) {

						return "errName";
					}
				}else{
					
					return "nullName";
				}
				
				if(user.getPhone()!=null){
					
					if(user.getPhone().equals(user2.getPhone())){
						
						return "errPhone";
					}
				}else{
						
					return "nullPhone";
				}				
				
				if(user.getEmail()!=null){
					
					if(user.getEmail().equals(user2.getEmail())){
						
						return "errEmail";
					}
				}else{
					
					return "nullEmail";
				}
			}

			String password = user.getPassword();
			String md5 = getMD5(password);
			user.setPassword(md5);
			
			userMapper.insertUser(user);
			return "yes";
		} catch (Exception e) {

			e.printStackTrace();
		}

		return "no";
	}

	public User login(String username,String password) {

		try {
			String md5 = getMD5(password);
			User user = userMapper.getUserByUsername(username);
			
			if(user!=null && md5.equals(user.getPassword())){
				
				return user;
			}
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		
		return null;
	}

	private String getMD5(String password) {

		String base = password + "/" + slat;
		String md5  = DigestUtils.md5DigestAsHex(base.getBytes());
		return md5;
	}
}
